package com.pcbly.web.components.utils.fileupload;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.pcbly.web.Constants;


/**
 * 上传Session实现
 * @author cleverpig
 *
 */
@SuppressWarnings("unchecked")
public class UploadSessionImpl implements UploadSession{
	private long timeToLive=Constants.TIME_TO_LIVE_MAX_MILLISECOND;
	private String id=null;
	//session属性集合
	private Map attributes = Collections.synchronizedMap(new HashMap());
	
	/**
	 * 构造上传会话：设置当前激活FUS和FUS列表
	 * @param uSessionId
	 */
	public UploadSessionImpl(String uSessionId){
		this.id=uSessionId;
		setFUSBeanList(new FileUploadStatusList());
		setActiveFUSBean(FileUploadStatusBeanManager.initFUSBean());
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public long getTimeToLive() {
		return timeToLive;
	}

	public void setTimeToLive(long timeToLive) {
		this.timeToLive = timeToLive;
	}
	
	public void setAttribute(String key,Object obj){
		attributes.put(key,obj);
	}
	
	public Object getAttribute(String key){
		if (attributes.containsKey(key)){
			return attributes.get(key);
		}
		else{
			return null;
		}
	}
	/**
	 * 获取当前激活的文件上传Bean
	 * @return
	 */
	public FileUploadStatus getActiveFUSBean() {
		if (getAttribute(Constants.FILE_UPLOADSTATUS_BEAN_KEY)!=null){
			return (FileUploadStatus)getAttribute(Constants.FILE_UPLOADSTATUS_BEAN_KEY);
		}
		else{
			return null;
		}
	}
	/**
	 * 设置当前激活的文件上传Bean
	 * @param uploadStatusBean
	 */
	public void setActiveFUSBean(FileUploadStatus uploadStatusBean) {
		setAttribute(Constants.FILE_UPLOADSTATUS_BEAN_KEY,uploadStatusBean);
	}
	/**
	 * 获得文件上传Bean列表
	 * @return
	 */
	public FileUploadStatusList getFUSBeanList() {
		if (getAttribute(Constants.FILE_UPLOADSTATUS_BEAN_LIST_KEY)!=null){
			return (FileUploadStatusList)getAttribute(Constants.FILE_UPLOADSTATUS_BEAN_LIST_KEY);
		}
		else{
			return null;
		}
	}
	/**
	 * 设置文件上传Bean列表
	 * @param uploadStatusBeanList
	 */
	public void setFUSBeanList(FileUploadStatusList uploadStatusBeanList) {
		setAttribute(Constants.FILE_UPLOADSTATUS_BEAN_LIST_KEY,uploadStatusBeanList);
	}
	public void addFUSBeanIntoList(FileUploadStatus fus){
		getFUSBeanList().add(fus);
	}
	public void removeFUSBeanFromList(int fusBeanId){
		getFUSBeanList().remove(fusBeanId);
	}
	/**
	 * 变老
	 * @param aDeltaMillis
	 */
	public void age(long aDeltaMillis) {
		timeToLive -= aDeltaMillis;
	}

	/**
	 * 是否已经过期
	 * @return
	 */
	public boolean isExpired() {
		return timeToLive <= 0;
	}

	/**
	 * 重新激活
	 */
	public void reActive() {
		timeToLive = Constants.TIME_TO_LIVE_MAX_MILLISECOND;
	}
	
	/**
	 * 启动session
	 */
	public void start() {
		UploadSessionManager.getInstance().addSession(this);
	}
	
	/**
	 * 停止session
	 *
	 */
	public void stop() {
		UploadSessionManager.getInstance().removeSession(this);
	}

}
